package com.culture.bootdemo.utils;

import com.culture.bootdemo.model.dto.MenuDTO;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: wenjl
 * @Date: 2022/11/3 16:39
 * @Description:
 */
public class MenuUtil {

    /**
     * 将菜单list转为树形结构
     *
     * @param menuList
     * @param parentId list中最高一级的父id
     * @return
     */
    public static List<MenuDTO> streamToTree(List<MenuDTO> menuList, Integer parentId) {
        List<MenuDTO> treeList = menuList.stream()
                // 过滤父节点
                .filter(parent -> parent.getPid().equals(parentId))
                // 把父节点children递归赋值成为子节点
                .map(child -> {
                    child.setChildren(streamToTree(menuList, child.getId()));
                    return child;
                }).collect(Collectors.toList());
        return treeList;
    }


    /**
     * 若传参为 07.12.36.00.00.00 则同时自身及返回三级父类
     *
     * @param catPath
     * @return
     */
    public static String[] getParentStoreCategory(String catPath) {
        List<String> result = new ArrayList<>();
        String[] catArr = catPath.split("\\.");

        if (catArr != null && catArr.length > 0) {
            int length = catArr.length;
            for (int i = 0; i < length; i++) {
                if ("00".equals(catArr[i])) {
                    break;
                } else {
                    StringBuilder cat = new StringBuilder();
                    for (int j = 0; j <= i; j++) {
                        if (cat.length() > 0) {
                            cat.append(".");
                        }
                        cat.append(catArr[j]);
                    }

                    for (int m = 1; m < length - i; m++) {
                        cat.append(".00");
                    }

                    result.add(cat.toString());
                }
            }
        }

        //逆序排序
        Collections.reverse(result);

        return result.toArray(new String[result.size()]);
    }


}
